<template>
    <!-- 在线支付 -->
    <div class="pay ffffff" v-loading.fullscreen.lock="loding">
        <navbar-breadcrumb>
            <template v-slot:bread>
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ name: 'myOrder' }">我的订单</el-breadcrumb-item>
                    <el-breadcrumb-item>在线支付</el-breadcrumb-item>
                </el-breadcrumb>
            </template>
        </navbar-breadcrumb>
        <div style="height:15px;background-color: #F5F6F7;"></div>
        <div class="payContent">
            <div class="payTotal padding15All">
                <p>需支付金额:<span>{{ total }}</span>元</p>
            </div>
            <div class="payType padding15All">
                <div class="padding15All">
                    <el-radio v-model="radio" label="1">使用第三方支付</el-radio>
                    <div class="type flexleft padding15All" v-if="radio == '1'">
                        <p>支付方式</p>
                        <div class="btn zfb " :class="{ 'active': active == 1 }" @click="changePayType(1)">
                            <img src="https://asset.tsign.cn/apps/saas-microfe/billing-front/prod/1.2.1/img/Alipay.d4993a1e.png"
                                alt="">
                        </div>
                        <div class="btn wx flexcenter" :class="{ 'active': active == 2 }" @click="changePayType(2)">
                            <img src="https://asset.tsign.cn/apps/saas-microfe/billing-front/prod/1.2.1/img/wei.dbf289ef.svg"
                                alt="">
                        </div>
                    </div>
                </div>
                <!-- <div class="padding15All">
                    <el-radio v-model="radio" label="2">对公支付</el-radio>
                    <div class="type flexleft padding15All" v-if="radio=='2'">
                        <p>支付方式</p>
                        <div class="btn card active flexcenter">
                            <img src="" alt="">
                            <p>银行转账</p>
                        </div>
                    </div>
                </div> -->
            </div>
            <div class="flexleft padding15All">
                <el-button type="primary" @click="buy">确认支付</el-button>
            </div>
        </div>
        <el-dialog :title="title" :visible.sync="dialogFormVisible" width="1000px">
            <div class="flexcenter" :class="{ 'bg': outer }">
                <Scancertificat type="pay" :url="scanurl" ref="scanmsg" @double="double"></Scancertificat>
                <div class="zhezhao flexcenter" v-if="outer">
                    <p>二维码过期!!!请刷新二维码</p>
                </div>
            </div>
        </el-dialog>

    </div>
</template>

	<!-- <script src="https://webapi.amap.com/loader.js"></script> -->
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
    securityJsCode: 'eb154374af6f8d50c8a25b132dec9d87',
}
import Scancertificat from "@/views/work/components/scanCertificat.vue"
import NavbarBreadcrumb from '../components/NavbarBreadcrumb.vue'
import { payAppreciationPC, getOrderState, paySignPurchasePC, weChatPayAppreciationPC } from '@/api/pay'
import Cookies from 'js-cookie'//获取cookies的信息
import { Message } from 'element-ui'
export default {
    components: { NavbarBreadcrumb, Scancertificat },
    data() {
        return {
            radio: '1',
            dialogFormVisible: false,
            scanurl: "",//二维码路径
            title: '',
            active: 1,
            type: '',
            signPayType: '',
            total: '',
            num: '',
            id: '',
            clientHome: '',
            outer: false,
            timer: null,
            geolocation: null,
            geocoder:null,
            address:"",
            loding:true
        }
    },
    created() {
        this.initMap();
    },
    watch:{
        address(newval){
            if(newval!=""){
                this.loding = false
            }
        }
    },
    mounted() {
        this.total = this.$route.params.total
        this.num = this.$route.params.num
        this.id = this.$route.params.id
        this.type = this.$route.params.type// 类型0鸿签1增值
        this.signPayType = this.$route.params.signPayType// 类型 0个人1企业

    },
    methods: {
        double() {
            // console.log('double');
            this.outer = false
            this.buy()
        },
        changePayType(type) {
            this.active = type
        },
        getOrderState(id) {// 查询订单支付状态
            getOrderState({
                orderNum: id,
            }).then(res => {
                // console.log(res.result);
                if (res.result.orderState == 1) {
                    Message({
                        message: '支付成功',
                        type: 'success',
                        duration: 2000,
                        onClose: () => {
                            this.$router.push({ name: 'myOrder' }, () => { })
                        }
                    })
                }
            }).catch(err => {
                console.log("请求失败", err)
            })
        },
        buy() {
            // console.log('99(((((((((((((((((((((');
            let _this = this

            if (this.active == 1) {
                this.title = '支付宝支付(请用支付宝扫描二维码)'
            } else if (this.active == 2) {
                this.title = '微信支付(请用微信扫描二维码)'
            }

            let pagFn;
            let obj;
            if (this.type == 0) {// 0鸿签1增值
                if (this.signPayType == 0) {// 0个人1企业
                    pagFn = paySignPurchasePC
                    obj = {
                        signPurchaseId: this.id,
                        enterpriseId: '',//企业id
                        signPayType: 0,// 购买主体类型 0-个人 1-企业
                    }
                } else if (this.signPayType == 1) {
                    pagFn = paySignPurchasePC
                    obj = {
                        signPurchaseId: this.id,
                        // enterpriseId:localStorage.getItem('companyid'),//企业id
                        enterpriseId: this.$route.params.enterpriseId,//企业id
                        signPayType: 1,// 购买主体类型 0-个人 1-企业
                    }
                }
            } else if (this.type == 1) {//0鸿签1增值
                if (this.signPayType == 0) {
                    pagFn = payAppreciationPC
                    // let userInfomsg=this.$store.state.user.userInfomsg
                    // console.log(userInfomsg);
                    obj = {
                        appreciationId: this.id,// 增值服务id
                        // enterpriseId:userInfomsg.lastLoginType==1?userInfomsg.lastLoginId:'',//企业id
                        // signPayType:userInfomsg.lastLoginType,// 购买主体类型 0-个人 1-企业
                        enterpriseId: '',//企业id
                        signPayType: 0,// 购买主体类型 0-个人 1-企业
                    }
                } else if (this.signPayType == 1) {
                    pagFn = payAppreciationPC
                    // let userInfomsg=this.$store.state.user.userInfomsg
                    // console.log(userInfomsg);
                    obj = {
                        appreciationId: this.id,// 增值服务id
                        // enterpriseId:userInfomsg.lastLoginType==1?userInfomsg.lastLoginId:'',//企业id
                        // signPayType:userInfomsg.lastLoginType,// 购买主体类型 0-个人 1-企业
                        enterpriseId: this.$route.params.enterpriseId,//企业id
                        signPayType: 1,// 购买主体类型 0-个人 1-企业
                    }
                }

            }

            pagFn({
                payNum: this.num,// 数量
                orderPayType: this.active == 1 ? 0 : 1,// 付款方式(0:支付宝1：微信
                userId: Cookies.get('admin_id'),//用户id
                addressName: this.address,//区域地址
                ...obj,
            }).then(res => {
                if (_this.active == 1) {
                    this.scanurl = res.result.paymentDate.expend.qrcode_url
                    this.dialogFormVisible = true

                    var i = 5
                    // timer=null;
                    clearInterval(this.timer);
                    this.timer = setInterval(function () {
                        if (i < 1) {
                            clearInterval(this.timer);
                            _this.outer = true
                        } else {
                            i--;
                            _this.getOrderState(res.result.orderNum)
                        }
                    }, 1000)
                } else if (_this.active == 2) {
                    let url = encodeURIComponent('https://www.signzg.com/pcpay/index.html')
                    let state = res.result.userOrderId
                    // let appid='wx4f1b59bec54793ba'
                    // this.scanurl=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`
                    this.scanurl = `https://www.signzg.com/pcpay/index.html?state=${state}`
                    this.dialogFormVisible = true

                    var i = 5
                    // timer=null;
                    clearInterval(this.timer);
                    this.timer = setInterval(function () {
                        if (i < 1) {
                            clearInterval(this.timer);
                            _this.outer = true
                        } else {
                            i--;
                            _this.getOrderState(state)
                        }
                    }, 1000)
                }

            }).catch(err => {
                console.log("请求失败", err)
            })
        },
        initMap() {
            AMapLoader.load({
                key: "9deb24044044ca2f33ee0120efd2de04", // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: [
                    'AMap.ToolBar',
                    'AMap.Scale',
                    'AMap.Geolocation',
                    'AMap.PlaceSearch',
                    'AMap.AutoComplete',
                    'AMap.Geocoder',
                    'AMap.CitySearch'
                ],
                resizeEnable: true,
            }).then((AMap) => {
                const that = this;
                that.getCurrentLocation();//获取当前定位
                that.geocoder = new AMap.Geocoder()
            }).catch(e => {
                console.log(e);
            })
        },
        //获取当前定位
        getCurrentLocation() {
            const that = this;
            that.geolocation = new AMap.Geolocation({
                timeout: 2000,          //超过3秒后停止定位，默认：5s
                enableHighAccuracy: true,
            });
            that.geolocation.getCurrentPosition(function (status, result) {
                //备注：getCurrentPosition方法会调用超时或失败：
                //Get geolocation time out：浏览器定位超时，包括原生的超时，可以适当增加超时属性的设定值以减少这一现象。
                //另外还有个别浏览器（如google Chrome浏览器等）本身的定位接口是黑洞，通过其请求定位完全没有回应，也会超时返回失败。
                //Get geolocation failed：定位失败，Chrome、火狐以及部分套壳浏览器接入的定位服务在国外，有较大限制，失败率高。
                // console.log(status, result,999);
                if (status == 'complete') {
                    that.onComplete(result)
                } else {
                    that.onError(result) //失败后可使用getCityInfo获取非精准定位（具体到省市）
                }
            });
        },
        //解析定位结果
        onComplete(data) {
            let lnglat = data.position;
            let that = this
            //经纬度转换为中文地址详情
            that.geocoder.getAddress(lnglat, function (status, result) {
                    // console.log(result, 888);
                if (status === 'complete' && result.regeocode) {
                    that.address = result.regeocode.addressComponent.province+","+ result.regeocode.addressComponent.city +","+ result.regeocode.addressComponent.district;
                } else {
                    that.$message.error('根据经纬度查询地址失败')
                    that.loding = false
                }
            })
        },
        //解析定位错误信息
        onError(data) {
            this.getLngLatLocation()
        },
        //在获取具体定位失败时调用的代码：（非精准定位！！！）
        getLngLatLocation() {
            const that = this;
            that.geolocation.getCityInfo(function (status, result) {
                if (status === 'complete') {
                    // let data = result.position
                    // console.log(result,888);
                    that.onComplete(result)
                } else {
                    that.$message.error('获取地址失败')
                    that.loding = false
                }
            })
        },
    }

}
</script>

<style lang="scss" scoped>
.pay {
    height: 100%;

    .payType>div {
        border: 1px solid #F5F6F7;
        margin-bottom: 20px;

        .btn {
            border: 1px solid #f3f3f3;
            text-align: center;
            width: 200px;
            height: 50px;
            margin-right: 20px;

            &.zfb {
                margin-left: 20px;

                img {
                    width: 100%;
                }
            }

            &.active {
                border: 1px solid #0975e0;
            }

            &.card {
                margin-left: 20px;

                img {
                    width: 40px;
                }
            }
        }
    }

    .payTotal {
        padding-top: 30px;
        border-bottom: 1px solid #F5F6F7;

        p {
            font-weight: 600;
            font-size: 14px;

            span {
                color: red;
                font-size: 25px;
            }
        }
    }

    .bg {
        position: relative;

        .zhezhao {
            width: 200px;
            height: 200px;
            position: absolute;
            top: 20px;
            background-color: #fff;
            color: #000;
            font-weight: bold;
            font-size: 20px;
            text-align: center;
        }
    }
}
</style>